home *** CD-ROM | disk | FTP | other *** search
/ BBS in a Box 5 / BBS in a Box -Volume V (BBS in a Box) (April 1992).iso / Files / Prog / M / MPWGCC (Misc).cpt / Bison / Documents / Info / bison.info-3 < prev    next >
Encoding:
Text File  |  1989-05-30  |  48.4 KB  |  1,302 lines  |  [TEXT/MPS ]

  1. Info file bison.info, produced by Makeinfo, -*- Text -*- from input
  2. file bison.texinfo.
  3.  
  4. This file documents the Bison parser generator.
  5.  
  6. Copyright (C) 1988, 1989 Free Software Foundation, Inc.
  7.  
  8. Permission is granted to make and distribute verbatim copies of this
  9. manual provided the copyright notice and this permission notice are
  10. preserved on all copies.
  11.  
  12. Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided also
  14. that the sections entitled ``GNU General Public License'' and
  15. ``Conditions for Using Bison'' are included exactly as in the
  16. original, and provided that the entire resulting derived work is
  17. distributed under the terms of a permission notice identical to this
  18. one.
  19.  
  20. Permission is granted to copy and distribute translations of this
  21. manual into another language, under the above conditions for modified
  22. versions, except that the sections entitled ``GNU General Public
  23. License'', ``Conditions for Using Bison'' and this permission notice
  24. may be included in translations approved by the Free Software
  25. Foundation instead of in the original English.
  26.  
  27.  
  28. 
  29. File: bison.info,  Node: Multiple Parsers,  Prev: Declarations,  Up: Grammar File
  30.  
  31. Multiple Parsers in the Same Program
  32. ====================================
  33.  
  34. Most programs that use Bison parse only one language and therefore
  35. contain only one Bison parser.  But what if you want to parse more
  36. than one language with the same program?  Here is what you must do:
  37.  
  38.    * Make each parser a pure parser (*note Pure Decl::.).  This gets
  39.      rid of global variables such as `yylval' which would otherwise
  40.      conflict between the various parsers, but it requires an
  41.      alternate calling convention for `yylex' (*note Pure Calling::.).
  42.  
  43.    * In each grammar file, define `yyparse' as a macro, expanding
  44.      into the name you want for that parser.  Put this definition in
  45.      the C declarations section (*note C Declarations::.).  For
  46.      example:
  47.  
  48.           %{
  49.           #define yyparse parse_algol
  50.           %}
  51.  
  52.      Then use the expanded name `parse_algol' in other source files
  53.      to call this parser.
  54.  
  55.    * If you want different lexical analyzers for each grammar, you
  56.      can define `yylex' as a macro, just like `yyparse'.  Use the
  57.      expanded name when you define `yylex' in another source file.
  58.  
  59.      If you define `yylex' in the grammar file itself, simply make it
  60.      static, like this:
  61.  
  62.           %{
  63.           static int yylex ();
  64.           %}
  65.           %%
  66.           ... GRAMMAR RULES ...
  67.           %%
  68.           static int
  69.           yylex (yylvalp, yyllocp)
  70.                YYSTYPE *yylvalp;
  71.                YYLTYPE *yyllocp;
  72.           { ... }
  73.  
  74.    * If you want a different `yyerror' function for each grammar, you
  75.      can use the same methods that work for `yylex'.
  76.  
  77.  
  78. 
  79. File: bison.info,  Node: Interface,  Next: Algorithm,  Prev: Grammar File,  Up: Top
  80.  
  81. Parser C-Language Interface
  82. ***************************
  83.  
  84. The Bison parser is actually a C function named `yyparse'.  Here we
  85. describe the interface conventions of `yyparse' and the other
  86. functions that it needs to use.
  87.  
  88. Keep in mind that the parser uses many C identifiers starting with
  89. `yy' and `YY' for internal purposes.  If you use such an identifier
  90. (aside from those in this manual) in an action or in additional C
  91. code in the grammar file, you are likely to run into trouble.
  92.  
  93. * Menu:
  94.  
  95. * Parser Function:: How to call `yyparse' and what it returns.
  96. * Lexical::         You must supply a function `yylex' which reads tokens.
  97. * Error Reporting:: You must supply a function `yyerror'.
  98. * Action Features:: Special features for use in actions.
  99.  
  100.  
  101. 
  102. File: bison.info,  Node: Parser Function,  Next: Lexical,  Prev: Interface,  Up: Interface
  103.  
  104. The Parser Function `yyparse'
  105. =============================
  106.  
  107. You call the function `yyparse' to cause parsing to occur.  This
  108. function reads tokens, executes actions, and ultimately returns when
  109. it encounters end-of-input or an unrecoverable syntax error.  You can
  110. also write an action which directs `yyparse' to return immediately
  111. without reading further.
  112.  
  113. The value returned by `yyparse' is 0 if parsing was successful
  114. (return is due to end-of-input).
  115.  
  116. The value is 1 if parsing failed (return is due to a syntax error).
  117.  
  118. In an action, you can cause immediate return from `yyparse' by using
  119. these macros:
  120.  
  121. `YYACCEPT'
  122.      Return immediately with value 0 (to report success).
  123.  
  124. `YYABORT'
  125.      Return immediately with value 1 (to report failure).
  126.  
  127.  
  128. 
  129. File: bison.info,  Node: Lexical,  Next: Error Reporting,  Prev: Parser Function,  Up: Interface
  130.  
  131. The Lexical Analyzer Function `yylex'
  132. =====================================
  133.  
  134. The "lexical analyzer" function, `yylex', recognizes tokens from the
  135. input stream and returns them to the parser.  Bison does not create
  136. this function automatically; you must write it so that `yyparse' can
  137. call it.  The function is sometimes referred to as a lexical scanner.
  138.  
  139. In simple programs, `yylex' is often defined at the end of the Bison
  140. grammar file.  If `yylex' is defined in a separate source file, you
  141. need to arrange for the token-type macro definitions to be available
  142. there.  To do this, use the `-d' option when you run Bison, so that
  143. it will write these macro definitions into a separate header file
  144. `NAME.tab.h' which you can include in the other source files that
  145. need it.  *Note Invocation::.
  146.  
  147. * Menu:
  148.  
  149. * Calling Convention::   How `yyparse' calls `yylex'.
  150. * Token Values::         How `yylex' must return the semantic value
  151.                            of the token it has read.
  152. * Token Positions::      How `yylex' must return the text position
  153.                            (line number, etc.) of the token, if the
  154.                            actions want that.
  155. * Pure Calling::         How the calling convention differs
  156.                            in a pure parser (*note Pure Decl::.).
  157.  
  158.  
  159. 
  160. File: bison.info,  Node: Calling Convention,  Next: Token Values,  Prev: Lexical,  Up: Lexical
  161.  
  162. Calling Convention for `yylex'
  163. ------------------------------
  164.  
  165. The value that `yylex' returns must be the numeric code for the type
  166. of token it has just found, or 0 for end-of-input.
  167.  
  168. When a token is referred to in the grammar rules by a name, that name
  169. in the parser file becomes a C macro whose definition is the proper
  170. numeric code for that token type.  So `yylex' can use the name to
  171. indicate that type.  *Note Symbols::.
  172.  
  173. When a token is referred to in the grammar rules by a character
  174. literal, the numeric code for that character is also the code for the
  175. token type.  So `yylex' can simply return that character code.  The
  176. null character must not be used this way, because its code is zero
  177. and that is what signifies end-of-input.
  178.  
  179. Here is an example showing these things:
  180.  
  181.      yylex()
  182.      {
  183.        ...
  184.        if (c == EOF)     /* Detect end of file.  */
  185.          return 0;
  186.        ...
  187.        if (c == '+' || c == '-')
  188.          return c;      /* Assume token type for `+' is '+'.  */
  189.        ...
  190.        return INT;      /* Return the type of the token.  */
  191.        ...
  192.      }
  193.  
  194. This interface has been designed so that the output from the `lex'
  195. utility can be used without change as the definition of `yylex'.
  196.  
  197.  
  198. 
  199. File: bison.info,  Node: Token Values,  Next: Token Positions,  Prev: Calling Convention,  Up: Lexical
  200.  
  201. Returning Semantic Values of Tokens
  202. -----------------------------------
  203.  
  204. In an ordinary (nonreentrant) parser, the semantic value of the token
  205. must be stored into the global variable `yylval'.  When you are using
  206. just one data type for semantic values, `yylval' has that type. 
  207. Thus, if the type is `int' (the default), you might write this in
  208. `yylex':
  209.  
  210.        ...
  211.        yylval = value;  /* Put value onto Bison stack.  */
  212.        return INT;      /* Return the type of the token.  */
  213.        ...
  214.  
  215.  When you are using multiple data types, `yylval''s type is a union
  216. made from the `%union' declaration (*note Union Decl::.).  So when
  217. you store a token's value, you must use the proper member of the union.
  218. If the `%union' declaration looks like this:
  219.  
  220.      %union {
  221.        int intval;
  222.        double val;
  223.        symrec *tptr;
  224.      }
  225.  
  226. then the code in `yylex' might look like this:
  227.  
  228.        ...
  229.        yylval.intval = value;  /* Put value onto Bison stack.  */
  230.        return INT;      /* Return the type of the token.  */
  231.        ...
  232.  
  233.  
  234. 
  235. File: bison.info,  Node: Token Positions,  Next: Pure Calling,  Prev: Token Values,  Up: Lexical
  236.  
  237. Reporting Textual Positions of Tokens
  238. -------------------------------------
  239.  
  240. If you are using the `@N'-feature (*note Action Features::.) in
  241. actions to keep track of the textual locations of tokens and
  242. groupings, then you must provide this information in `yylex'.  The
  243. function `yyparse' expects to find the textual location of a token
  244. just parsed in the global variable `yylloc'.  So `yylex' must store
  245. the proper data in that variable.  The value of `yylloc' is a
  246. structure and you need only initialize the members that are going to
  247. be used by the actions.  The four members are called `first_line',
  248. `first_column', `last_line' and `last_column'.  Note that the use of
  249. this feature makes the parser noticeably slower.
  250.  
  251. The data type of `yylloc' has the name `YYLTYPE'.
  252.  
  253.  
  254. 
  255. File: bison.info,  Node: Pure Calling,  Prev: Token Positions,  Up: Lexical
  256.  
  257. Calling Convention for Pure Parsers
  258. -----------------------------------
  259.  
  260. When you use the Bison declaration `%pure_parser' to request a pure,
  261. reentrant parser, the global communication variables `yylval' and
  262. `yylloc' cannot be used.  (*Note Pure Decl::.)  In such parsers the
  263. two global variables are replaced by pointers passed as arguments to
  264. `yylex'.  You must declare them as shown here, and pass the
  265. information back by storing it through those pointers.
  266.  
  267.      yylex (lvalp, llocp)
  268.           YYSTYPE *lvalp;
  269.           YYLTYPE *llocp;
  270.      {
  271.        ...
  272.        *lvalp = value;  /* Put value onto Bison stack.  */
  273.        return INT;      /* Return the type of the token.  */
  274.        ...
  275.      }
  276.  
  277.  
  278. 
  279. File: bison.info,  Node: Error Reporting,  Next: Action Features,  Prev: Lexical,  Up: Interface
  280.  
  281. The Error Reporting Function `yyerror'
  282. ======================================
  283.  
  284. The Bison parser detects a "parse error" or "syntax error" whenever
  285. it reads a token which cannot satisfy any syntax rule.  A action in
  286. the grammar can also explicitly proclaim an error, using the macro
  287. `YYERROR' (*note Action Features::.).
  288.  
  289. The Bison parser expects to report the error by calling an error
  290. reporting function named `yyerror', which you must supply.  It is
  291. called by `yyparse' whenever a syntax error is found, and it receives
  292. one argument.  For a parse error, the string is always `"parse error"'.
  293.  
  294. The parser can detect one other kind of error: stack overflow.  This
  295. happens when the input contains constructions that are very deeply
  296. nested.  It isn't likely you will encounter this, since the Bison
  297. parser extends its stack automatically up to a very large limit.  But
  298. if overflow happens, `yyparse' calls `yyerror' in the usual fashion,
  299. except that the argument string is `"parser stack overflow"'.
  300.  
  301. The following definition suffices in simple programs:
  302.  
  303.      yyerror (s)
  304.           char *s;
  305.      {
  306.  
  307.        fprintf (stderr, "%s\n", s);
  308.      }
  309.  
  310. After `yyerror' returns to `yyparse', the latter will attempt error
  311. recovery if you have written suitable error recovery grammar rules
  312. (*note Error Recovery::.).  If recovery is impossible, `yyparse' will
  313. immediately return 1.
  314.  
  315. The variable `yynerrs' contains the number of syntax errors
  316. encountered so far.  Normally this variable is global; but if you
  317. request a pure parser (*note Pure Decl::.) then it is a local
  318. variable which only the actions can access.
  319.  
  320.  
  321. 
  322. File: bison.info,  Node: Action Features,  Prev: Error Reporting,  Up: Interface
  323.  
  324. Special Features for Use in Actions
  325. ===================================
  326.  
  327. Here is a table of Bison constructs, variables and macros that are
  328. useful in actions.
  329.  
  330. `$$'
  331.      Acts like a variable that contains the semantic value for the
  332.      grouping made by the current rule.  *Note Actions::.
  333.  
  334. `$N'
  335.      Acts like a variable that contains the semantic value for the
  336.      Nth component of the current rule.  *Note Actions::.
  337.  
  338. `$<TYPEALT>$'
  339.      Like `$$' but specifies alternative TYPEALT in the union
  340.      specified by the `%union' declaration.  *Note Action Types::.
  341.  
  342. `$<TYPEALT>N'
  343.      Like `$N' but specifies alternative TYPEALT in the union
  344.      specified by the `%union' declaration.  *Note Action Types::.
  345.  
  346. `YYABORT;'
  347.      Return immediately from `yyparse', indicating failure.  *Note
  348.      Parser Function::.
  349.  
  350. `YYACCEPT;'
  351.      Return immediately from `yyparse', indicating success.  *Note
  352.      Parser Function::.
  353.  
  354. `YYEMPTY'
  355.      Value stored in `yychar' when there is no look-ahead token.
  356.  
  357. `YYERROR;'
  358.      Cause an immediate syntax error.  This causes `yyerror' to be
  359.      called, and then error recovery begins.  *Note Error Recovery::.
  360.  
  361. `yychar'
  362.      Variable containing the current look-ahead token.  (In a pure
  363.      parser, this is actually a local variable within `yyparse'.) 
  364.      When there is no look-ahead token, the value `YYERROR' is stored
  365.      here.  *Note Look-Ahead::.
  366.  
  367. `yyclearin;'
  368.      Discard the current look-ahead token.  This is useful primarily
  369.      in error rules.  *Note Error Recovery::.
  370.  
  371. `yyerrok;'
  372.      Resume generating error messages immediately for subsequent
  373.      syntax errors.  This is useful primarily in error rules.  *Note
  374.      Error Recovery::.
  375.  
  376. `@N'
  377.      Acts like a structure variable containing information on the
  378.      line numbers and column numbers of the Nth component of the
  379.      current rule.  The structure has four members, like this:
  380.  
  381.           struct {
  382.             int first_line, last_line;
  383.             int first_column, last_column;
  384.           };
  385.  
  386.      Thus, to get the starting line number of the third component,
  387.      use `@3.first_line'.
  388.  
  389.      In order for the members of this structure to contain valid
  390.      information, you must make `yylex' supply this information about
  391.      each token.  If you need only certain members, then `yylex' need
  392.      only fill in those members.
  393.  
  394.      The use of this feature makes the parser noticeably slower.
  395.  
  396.  
  397. 
  398. File: bison.info,  Node: Algorithm,  Next: Error Recovery,  Prev: Interface,  Up: Top
  399.  
  400. The Algorithm of the Bison Parser
  401. *********************************
  402.  
  403. As Bison reads tokens, it pushes them onto a stack along with their
  404. semantic values.  The stack is called the "parser stack".  Pushing a
  405. token is traditionally called "shifting".
  406.  
  407. For example, suppose the infix calculator has read `1 + 5 *', with a
  408. `3' to come.  The stack will have four elements, one for each token
  409. that was shifted.
  410.  
  411. But the stack does not always have an element for each token read. 
  412. When the last N tokens and groupings shifted match the components of
  413. a grammar rule, they can be combined according to that rule.  This is
  414. called "reduction".  Those tokens and groupings are replaced on the
  415. stack by a single grouping whose symbol is the result (left hand
  416. side) of that rule.  Running the rule's action is part of the process
  417. of reduction, because this is what computes the semantic value of the
  418. resulting grouping.
  419.  
  420. For example, if the infix calculator's parser stack contains this:
  421.  
  422.      1 + 5 * 3
  423.  
  424. and the next input token is a newline character, then the last three
  425. elements can be reduced to 15 via the rule:
  426.  
  427.      expr: expr '*' expr;
  428.  
  429. Then the stack contains just these three elements:
  430.  
  431.      1 + 15
  432.  
  433. At this point, another reduction can be made, resulting in the single
  434. value 16.  Then the newline token can be shifted.
  435.  
  436. The parser tries, by shifts and reductions, to reduce the entire
  437. input down to a single grouping whose symbol is the grammar's
  438. start-symbol (*note Language and Grammar::.).
  439.  
  440. This kind of parser is known in the literature as a bottom-up parser.
  441.  
  442. * Menu:
  443.  
  444. * Look-Ahead::          Parser looks one token ahead when deciding what to do.
  445. * Shift/Reduce::        Conflicts: when either shifting or reduction is valid.
  446. * Precedence::          Operator precedence works by resolving conflicts.
  447. * Contextual Precedence:: When an operator's precedence depends on context.
  448. * Parser States::       The parser is a finite-state-machine with stack.
  449. * Reduce/Reduce::       When two rules are applicable in the same situation.
  450.  
  451.  
  452. 
  453. File: bison.info,  Node: Look-Ahead,  Next: Shift/Reduce,  Prev: Algorithm,  Up: Algorithm
  454.  
  455. Look-Ahead Tokens
  456. =================
  457.  
  458. The Bison parser does *not* always reduce immediately as soon as the
  459. last N tokens and groupings match a rule.  This is because such a
  460. simple strategy is inadequate to handle most languages.  Instead,
  461. when a reduction is possible, the parser sometimes ``looks ahead'' at
  462. the next token in order to decide what to do.
  463.  
  464. When a token is read, it is not immediately shifted; first it becomes
  465. the "look-ahead token", which is not on the stack.  Now the parser
  466. can perform one or more reductions of tokens and groupings on the
  467. stack, while the look-ahead token remains off to the side.  When no
  468. more reductions should take place, the look-ahead token is shifted
  469. onto the stack.  This does not mean that all possible reductions have
  470. been done; depending on the token type of the look-ahead token, some
  471. rules may choose to delay their application.
  472.  
  473. Here is a simple case where look-ahead is needed.  These three rules
  474. define expressions which contain binary addition operators and
  475. postfix unary factorial operators (`!'), and allow parentheses for
  476. grouping.
  477.  
  478.      expr:     term '+' expr
  479.              | term
  480.              ;
  481.      
  482.      term:     '(' expr ')'
  483.              | term '!'
  484.              | NUMBER
  485.              ;
  486.  
  487. Suppose that the tokens `1 + 2' have been read and shifted; what
  488. should be done?  If the following token is `)', then the first three
  489. tokens must be reduced to form an `expr'.  This is the only valid
  490. course, because shifting the `)' would produce a sequence of symbols
  491. `term ')'', and no rule allows this.
  492.  
  493. If the following token is `!', then it must be shifted immediately so
  494. that `2 !' can be reduced to make a `term'.  If instead the parser
  495. were to reduce before shifting, `1 + 2' would become an `expr'.  It
  496. would then be impossible to shift the `!' because doing so would
  497. produce on the stack the sequence of symbols `expr '!''.  No rule
  498. allows that sequence.
  499.  
  500. The current look-ahead token is stored in the variable `yychar'. 
  501. *Note Action Features::.
  502.  
  503.  
  504. 
  505. File: bison.info,  Node: Shift/Reduce,  Next: Precedence,  Prev: Look-Ahead,  Up: Algorithm
  506.  
  507. Shift/Reduce Conflicts
  508. ======================
  509.  
  510. Suppose we are parsing a language which has if-then and if-then-else
  511. statements, with a pair of rules like this:
  512.  
  513.      if_stmt:
  514.                IF expr THEN stmt
  515.              | IF expr THEN stmt ELSE stmt
  516.              ;
  517.  
  518. (Here we assume that `IF', `THEN' and `ELSE' are terminal symbols for
  519. specific keyword tokens.)
  520.  
  521. When the `ELSE' token is read and becomes the look-ahead token, the
  522. contents of the stack (assuming the input is valid) are just right
  523. for reduction by the first rule.  But it is also legitimate to shift
  524. the `ELSE', because that would lead to eventual reduction by the
  525. second rule.
  526.  
  527. This situation, where either a shift or a reduction would be valid,
  528. is called a "shift/reduce conflict".  Bison is designed to resolve
  529. these conflicts by choosing to shift, unless otherwise directed by
  530. operator precedence declarations.  To see the reason for this, let's
  531. contrast it with the other alternative.
  532.  
  533. Since the parser prefers to shift the `ELSE', the result is to attach
  534. the else-clause to the innermost if-statement, making these two
  535. inputs equivalent:
  536.  
  537.      if x then if y then win(); else lose;
  538.      
  539.      if x then do; if y then win(); else lose; end;
  540.  
  541. But if the parser chose to reduce when possible rather than shift,
  542. the result would be to attach the else-clause to the outermost
  543. if-statement, making these two inputs equivalent:
  544.  
  545.      if x then if y then win(); else lose;
  546.      
  547.      if x then do; if y then win(); end; else lose;
  548.  
  549. The conflict exists because the grammar as written is ambiguous:
  550. either parsing of the simple nested if-statement is legitimate.  The
  551. established convention is that these ambiguities are resolved by
  552. attaching the else-clause to the innermost if-statement; this is what
  553. Bison accomplishes by choosing to shift rather than reduce.  (It
  554. would ideally be cleaner to write an unambiguous grammar, but that is
  555. very hard to do in this case.) This particular ambiguity was first
  556. encountered in the specifications of Algol 60 and is called the
  557. ``dangling `else''' ambiguity.
  558.  
  559. To avoid warnings from Bison about predictable, legitimate
  560. shift/reduce conflicts, use the `%expect N' declaration.  There will
  561. be no warning as long as the number of shift/reduce conflicts is
  562. exactly N.  *Note Expect Decl::.
  563.  
  564.  
  565. 
  566. File: bison.info,  Node: Precedence,  Next: Contextual Precedence,  Prev: Shift/Reduce,  Up: Algorithm
  567.  
  568. Operator Precedence
  569. ===================
  570.  
  571. Another situation where shift/reduce conflicts appear is in
  572. arithmetic expressions.  Here shifting is not always the preferred
  573. resolution; the Bison declarations for operator precedence allow you
  574. to specify when to shift and when to reduce.
  575.  
  576. * Menu:
  577.  
  578. * Why Precedence::      An example showing why precedence is needed.
  579. * Using Precedence::    How to specify precedence in Bison grammars.
  580. * Precedence Examples:: How these features are used in the previous example.
  581. * How Precedence::      How they work.
  582.  
  583.  
  584. 
  585. File: bison.info,  Node: Why Precedence,  Next: Using Precedence,  Prev: Precedence,  Up: Precedence
  586.  
  587. When Precedence is Needed
  588. -------------------------
  589.  
  590. Consider the following ambiguous grammar fragment (ambiguous because
  591. the input `1 - 2 * 3' can be parsed in two different ways):
  592.  
  593.      expr:     expr '-' expr
  594.              | expr '*' expr
  595.              | expr '<' expr
  596.              | '(' expr ')'
  597.              ...
  598.              ;
  599.  
  600. Suppose the parser has seen the tokens `1', `-' and `2'; should it
  601. reduce them via the rule for the addition operator?  It depends on
  602. the next token.  Of course, if the next token is `)', we must reduce;
  603. shifting is invalid because no single rule can reduce the token
  604. sequence `- 2 )' or anything starting with that.  But if the next
  605. token is `*' or `<', we have a choice: either shifting or reduction
  606. would allow the parse to complete, but with different results.
  607.  
  608. To decide which one Bison should do, we must consider the results. 
  609. If the next operator token OP is shifted, then it must be reduced
  610. first in order to permit another opportunity to reduce the sum.  The
  611. result is (in effect) `1 - (2 OP 3)'.  On the other hand, if the
  612. subtraction is reduced before shifting OP, the result is
  613. `(1 - 2) OP 3'.  Clearly, then, the choice of shift or reduce
  614. should depend on the relative precedence of the operators `-' and OP:
  615. `*' should be shifted first, but not `<'.
  616.  
  617. What about input like `1 - 2 - 5'; should this be `(1 - 2) - 5' or
  618. `1 - (2 - 5)'?  For most operators we prefer the former, which is
  619. called "left association".  The latter alternative, "right
  620. association", is desirable for assignment operators.  The choice of
  621. left or right association is a matter of whether the parser chooses
  622. to shift or reduce when the stack contains `1 - 2' and the look-ahead
  623. token is `-': shifting makes right-associativity.
  624.  
  625.  
  626. 
  627. File: bison.info,  Node: Using Precedence,  Next: Precedence Examples,  Prev: Why Precedence,  Up: Precedence
  628.  
  629. How to Specify Operator Precedence
  630. ----------------------------------
  631.  
  632. Bison allows you to specify these choices with the operator
  633. precedence declarations `%left' and `%right'.  Each such declaration
  634. contains a list of tokens, which are operators whose precedence and
  635. associativity is being declared.  The `%left' declaration makes all
  636. those operators left-associative and the `%right' declaration makes
  637. them right-associative.  A third alternative is `%nonassoc', which
  638. declares that it is a syntax error to find the same operator twice
  639. ``in a row''.
  640.  
  641. The relative precedence of different operators is controlled by the
  642. order in which they are declared.  The first `%left' or `%right'
  643. declaration declares the operators whose precedence is lowest, the
  644. next such declaration declares the operators whose precedence is a
  645. little higher, and so on.
  646.  
  647.  
  648. 
  649. File: bison.info,  Node: Precedence Examples,  Next: How Precedence,  Prev: Using Precedence,  Up: Precedence
  650.  
  651. Precedence Examples
  652. -------------------
  653.  
  654. In our example, we would want the following declarations:
  655.  
  656.      %left '<'
  657.      %left '-'
  658.      %left '*'
  659.  
  660. In a more complete example, which supports other operators as well,
  661. we would declare them in groups of equal precedence.  For example,
  662. `'+'' is declared with `'-'':
  663.  
  664.      %left '<' '>' '=' NE LE GE
  665.      %left '+' '-'
  666.      %left '*' '/'
  667.  
  668. (Here `NE' and so on stand for the operators for ``not equal'' and so
  669. on.  We assume that these tokens are more than one character long and
  670. therefore are represented by names, not character literals.)
  671.  
  672.  
  673. 
  674. File: bison.info,  Node: How Precedence,  Prev: Precedence Examples,  Up: Precedence
  675.  
  676. How Precedence Works
  677. --------------------
  678.  
  679. The first effect of the precedence declarations is to assign
  680. precedence levels to the terminal symbols declared.  The second
  681. effect is to assign precedence levels to certain rules: each rule
  682. gets its precedence from the last terminal symbol mentioned in the
  683. components.  (You can also specify explicitly the precedence of a
  684. rule.  *Note Contextual Precedence::.)
  685.  
  686. Finally, the resolution of conflicts works by comparing the
  687. precedence of the rule being considered with that of the look-ahead
  688. token.  If the token's precedence is higher, the choice is to shift. 
  689. If the rule's precedence is higher, the choice is to reduce.  If they
  690. have equal precedence, the choice is made based on the associativity
  691. of that precedence level.  The verbose output file made by `-v'
  692. (*note Invocation::.) says how each conflict was resolved.
  693.  
  694. Not all rules and not all tokens have precedence.  If either the rule
  695. or the look-ahead token has no precedence, then the default is to
  696. shift.
  697.  
  698.  
  699. 
  700. File: bison.info,  Node: Contextual Precedence,  Next: Parser States,  Prev: Precedence,  Up: Algorithm
  701.  
  702. Operators with Context-Dependent Precedence
  703. ===========================================
  704.  
  705. Often the precedence of an operator depends on the context.  This
  706. sounds outlandish at first, but it is really very common.  For
  707. example, a minus sign typically has a very high precedence as a unary
  708. operator, and a somewhat lower precedence (lower than multiplication)
  709. as a binary operator.
  710.  
  711. The Bison precedence declarations, `%left', `%right' and `%nonassoc',
  712. can only be used once for a given token; so a token has only one
  713. precedence declared in this way.  For context-dependent precedence,
  714. you need to use an additional mechanism: the `%prec' modifier for
  715. rules.
  716.  
  717. The `%prec' modifier declares the precedence of a particular rule by
  718. specifying a terminal symbol whose predecence should be used for that
  719. rule.  It's not necessary for that symbol to appear otherwise in the
  720. rule.  The modifier's syntax is:
  721.  
  722.      %prec TERMINAL-SYMBOL
  723.  
  724. and it is written after the components of the rule.  Its effect is to
  725. assign the rule the precedence of TERMINAL-SYMBOL, overriding the
  726. precedence that would be deduced for it in the ordinary way.  The
  727. altered rule precedence then affects how conflicts involving that
  728. rule are resolved (*note Precedence::.).
  729.  
  730. Here is how `%prec' solves the problem of unary minus.  First,
  731. declare a precedence for a fictitious terminal symbol named `UMINUS'.
  732. There are no tokens of this type, but the symbol serves to stand for
  733. its precedence:
  734.  
  735.      ...
  736.      %left '+' '-'
  737.      %left '*'
  738.      %left UMINUS
  739.  
  740. Now the precedence of `UMINUS' can be used in specific rules:
  741.  
  742.      exp:    ...
  743.              | exp '-' exp
  744.              ...
  745.              | '-' exp %prec UMINUS
  746.  
  747.  
  748. 
  749. File: bison.info,  Node: Parser States,  Next: Reduce/Reduce,  Prev: Contextual Precedence,  Up: Algorithm
  750.  
  751. Parser States
  752. =============
  753.  
  754. The function `yyparse' is implemented using a finite-state machine. 
  755. The values pushed on the parser stack are not simply token type
  756. codes; they represent the entire sequence of terminal and nonterminal
  757. symbols at or near the top of the stack.  The current state collects
  758. all the information about previous input which is relevant to
  759. deciding what to do next.
  760.  
  761. Each time a look-ahead token is read, the current parser state
  762. together with the type of look-ahead token are looked up in a table. 
  763. This table entry can say, ``Shift the look-ahead token.''  In this
  764. case, it also specifies the new parser state, which is pushed onto
  765. the top of the parser stack.  Or it can say, ``Reduce using rule
  766. number N.'' This means that a certain of tokens or groupings are
  767. taken off the top of the stack, and replaced by one grouping.  In
  768. other words, that number of states are popped from the stack, and one
  769. new state is pushed.
  770.  
  771. There is one other alternative: the table can say that the look-ahead
  772. token is erroneous in the current state.  This causes error
  773. processing to begin (*note Error Recovery::.).
  774.  
  775.  
  776. 
  777. File: bison.info,  Node: Reduce/Reduce,  Prev: Parser States,  Up: Algorithm
  778.  
  779. Reduce/Reduce conflicts
  780. =======================
  781.  
  782. A reduce/reduce conflict occurs if there are two or more rules that
  783. apply to the same sequence of input.  This usually indicates a
  784. serious error in the grammar.
  785.  
  786. For example, here is an erroneous attempt to define a sequence of
  787. zero or more `word' groupings.
  788.  
  789.      sequence: /* empty */
  790.                      { printf ("empty sequence\n"); }
  791.              | word
  792.                      { printf ("single word %s\n", $1); }
  793.              | sequence word
  794.                      { printf ("added word %s\n", $2); }
  795.              ;
  796.  
  797. The error is an ambiguity: there is more than one way to parse a
  798. single `word' into a `sequence'.  It could be reduced directly via
  799. the second rule.  Alternatively, nothing-at-all could be reduced into
  800. a `sequence' via the first rule, and this could be combined with the
  801. `word' using the third rule.
  802.  
  803. You might think that this is a distinction without a difference,
  804. because it does not change whether any particular input is valid or
  805. not.  But it does affect which actions are run.  One parsing order
  806. runs the second rule's action; the other runs the first rule's action
  807. and the third rule's action.  In this example, the output of the
  808. program changes.
  809.  
  810. Bison resolves a reduce/reduce conflict by choosing to use the rule
  811. that appears first in the grammar, but it is very risky to rely on
  812. this.  Every reduce/reduce conflict must be studied and usually
  813. eliminated.  Here is the proper way to define `sequence':
  814.  
  815.      sequence: /* empty */
  816.                      { printf ("empty sequence\n"); }
  817.              | sequence word
  818.                      { printf ("added word %s\n", $2); }
  819.              ;
  820.  
  821. Here is another common error that yields a reduce/reduce conflict:
  822.  
  823.      sequence: /* empty */
  824.              | sequence words
  825.              | sequence redirects
  826.              ;
  827.      
  828.      words:    /* empty */
  829.              | words word
  830.              ;
  831.      
  832.      redirects:/* empty */
  833.              | redirects redirect
  834.              ;
  835.  
  836. The intention here is to define a sequence which can contain either
  837. `word' or `redirect' groupings.  The individual definitions of
  838. `sequence', `words' and `redirects' are error-free, but the three
  839. together make a subtle ambiguity: even an empty input can be parsed
  840. in infinitely many ways!
  841.  
  842. Consider: nothing-at-all could be a `words'.  Or it could be two
  843. `words' in a row, or three, or any number.  It could equally well be
  844. a `redirects', or two, or any number.  Or it could be a `words'
  845. followed by three `redirects' and another `words'.  And so on.
  846.  
  847. Here are two ways to correct these rules.  First, to make it a single
  848. level of sequence:
  849.  
  850.      sequence: /* empty */
  851.              | sequence word
  852.              | sequence redirect
  853.              ;
  854.  
  855. Second, to prevent either a `words' or a `redirects' from being empty:
  856.  
  857.      sequence: /* empty */
  858.              | sequence words
  859.              | sequence redirects
  860.              ;
  861.      
  862.      words:    word
  863.              | words word
  864.              ;
  865.      
  866.      redirects:redirect
  867.              | redirects redirect
  868.              ;
  869.  
  870.  
  871. 
  872. File: bison.info,  Node: Error Recovery,  Next: Context Dependency,  Prev: Algorithm,  Up: Top
  873.  
  874. Error Recovery
  875. **************
  876.  
  877. It is not usually acceptable to have the program terminate on a parse
  878. error.  For example, a compiler should recover sufficiently to parse
  879. the rest of the input file and check it for errors; a calculator
  880. should accept another expression.
  881.  
  882. In a simple interactive command parser where each input is one line,
  883. it may be sufficient to allow `yyparse' to return 1 on error and have
  884. the caller ignore the rest of the input line when that happens (and
  885. then call `yyparse' again).  But this is inadequate for a compiler,
  886. because it forgets all the syntactic context leading up to the error.
  887. A syntax error deep within a function in the compiler input should
  888. not cause the compiler to treat the following line like the beginning
  889. of a source file.
  890.  
  891. You can define how to recover from a syntax error by writing rules to
  892. recognize the special token `error'.  This is a terminal symbol that
  893. is always defined (you need not declare it) and reserved for error
  894. handling.  The Bison parser generates an `error' token whenever a
  895. syntax error happens; if you have provided a rule to recognize this
  896. token in the current context, the parse can continue.  For example:
  897.  
  898.      stmnts:  /* empty string */
  899.              | stmnts '\n'
  900.              | stmnts exp '\n'
  901.              | stmnts error '\n'
  902.  
  903. The fourth rule in this example says that an error followed by a
  904. newline makes a valid addition to any `stmnts'.
  905.  
  906. What happens if a syntax error occurs in the middle of an `exp'?  The
  907. error recovery rule, interpreted strictly, applies to the precise
  908. sequence of a `stmnts', an `error' and a newline.  If an error occurs
  909. in the middle of an `exp', there will probably be some additional
  910. tokens and subexpressions on the stack after the last `stmnts', and
  911. there will be tokens to read before the next newline.  So the rule is
  912. not applicable in the ordinary way.
  913.  
  914. But Bison can force the situation to fit the rule, by discarding part
  915. of the semantic context and part of the input.  First it discards
  916. states and objects from the stack until it gets back to a state in
  917. which the `error' token is acceptable.  (This means that the
  918. subexpressions already parsed are discarded, back to the last
  919. complete `stmnts'.)  At this point the `error' token can be shifted. 
  920. Then, if the old look-ahead token is not acceptable to be shifted
  921. next, the parser reads tokens and discards them until it finds a
  922. token which is acceptable.  In this example, Bison reads and discards
  923. input until the next newline so that the fourth rule can apply.
  924.  
  925. The choice of error rules in the grammar is a choice of strategies
  926. for error recovery.  A simple and useful strategy is simply to skip
  927. the rest of the current input line or current statement if an error
  928. is detected:
  929.  
  930.      stmnt: error ';'  /* on error, skip until ';' is read */
  931.  
  932. It is also useful to recover to the matching close-delimiter of an
  933. opening-delimiter that has already been parsed.  Otherwise the
  934. close-delimiter will probably appear to be unmatched, and generate
  935. another, spurious error message:
  936.  
  937.      primary:  '(' expr ')'
  938.              | '(' error ')'
  939.              ...
  940.              ;
  941.  
  942. Error recovery strategies are necessarily guesses.  When they guess
  943. wrong, one syntax error often leads to another.  In the above
  944. example, the error recovery rule guesses that an error is due to bad
  945. input within one `stmnt'.  Suppose that instead a spurious semicolon
  946. is inserted in the middle of a valid `stmnt'.  After the error
  947. recovery rule recovers from the first error, another syntax error
  948. will be found straightaway, since the text following the spurious
  949. semicolon is also an invalid `stmnt'.
  950.  
  951. To prevent an outpouring of error messages, the parser will output no
  952. error message for another syntax error that happens shortly after the
  953. first; only after three consecutive input tokens have been
  954. successfully shifted will error messages resume.
  955.  
  956. Note that rules which accept the `error' token may have actions, just
  957. as any other rules can.
  958.  
  959. You can make error messages resume immediately by using the macro
  960. `yyerrok' in an action.  If you do this in the error rule's action,
  961. no error messages will be suppressed.  This macro requires no
  962. arguments; `yyerrok;' is a valid C statement.
  963.  
  964. The previous look-ahead token is reanalyzed immediately after an
  965. error.  If this is unacceptable, then the macro `yyclearin' may be
  966. used to clear this token.  Write the statement `yyclearin;' in the
  967. error rule's action.
  968.  
  969. For example, suppose that on a parse error, an error handling routine
  970. is called that advances the input stream to some point where parsing
  971. should once again commence.  The next symbol returned by the lexical
  972. scanner is probably correct.  The previous look-ahead token ought to
  973. be discarded with `yyclearin;'.
  974.  
  975.  
  976. 
  977. File: bison.info,  Node: Context Dependency,  Next: Debugging,  Prev: Error Recovery,  Up: Top
  978.  
  979. Handling Context Dependencies
  980. *****************************
  981.  
  982. The Bison paradigm is to parse tokens first, then group them into
  983. larger syntactic units.  In many languages, the meaning of a token is
  984. affected by its context.  Although this violates the Bison paradigm,
  985. certain techniques (known as "kludges") may enable you to write Bison
  986. parsers for such languages.
  987.  
  988. * Menu:
  989.  
  990. * Semantic Tokens::     Token parsing can depend on the semantic context.
  991. * Lexical Tie-ins::     Token parsing can depend on the syntactic context.
  992. * Tie-in Recovery::     Lexical tie-ins have implications for how
  993.               error recovery rules must be written.
  994.  
  995.  (Actually, ``kludge'' means any technique that gets its job done but
  996. is neither clean nor robust.)
  997.  
  998.  
  999. 
  1000. File: bison.info,  Node: Semantic Tokens,  Next: Lexical Tie-ins,  Prev: Context Dependency,  Up: Context Dependency
  1001.  
  1002. Semantic Info in Token Types
  1003. ============================
  1004.  
  1005. The C language has a context dependency: the way an identifier is
  1006. used depends on what its current meaning is.  For example, consider
  1007. this:
  1008.  
  1009.      foo (x);
  1010.  
  1011. This looks like a function call statement, but if `foo' is a typedef
  1012. name, then this is actually a declaration of `x'.  How can a Bison
  1013. parser for C decide how to parse this input?
  1014.  
  1015. The method used in GNU C is to have two different token types,
  1016. `IDENTIFIER' and `TYPENAME'.  When `yylex' finds an identifier, it
  1017. looks up the current declaration of the identifier in order to decide
  1018. which token type to return: `TYPENAME' if the identifier is declared
  1019. as a typedef, `IDENTIFIER' otherwise.
  1020.  
  1021. The grammar rules can then express the context dependency by the
  1022. choice of token type to recognize.  `IDENTIFIER' is accepted as an
  1023. expression, but `TYPENAME' is not.  `TYPENAME' can start a
  1024. declaration, but `IDENTIFIER' cannot.  In contexts where the meaning
  1025. of the identifier is *not* significant, such as in declarations that
  1026. can shadow a typedef name, either `TYPENAME' or `IDENTIFIER' is
  1027. accepted--there is one rule for each of the two token types.
  1028.  
  1029. This technique is simple to use if the decision of which kinds of
  1030. identifiers to allow is made at a place close to where the identifier
  1031. is parsed.  But in C this is not always so: C allows a declaration to
  1032. redeclare a typedef name provided an explicit type has been specified
  1033. earlier:
  1034.  
  1035.      typedef int foo, bar, lose;
  1036.      static foo (bar);        /* redeclare `bar' as static variable */
  1037.      static int foo (lose);   /* redeclare `foo' as function */
  1038.  
  1039. Unfortunately, the name being declared is separated from the
  1040. declaration construct itself by a complicated syntactic
  1041. structure--the ``declarator''.
  1042.  
  1043. As a result, the part of Bison parser for C needs to be duplicated,
  1044. with all the nonterminal names changed: once for parsing a
  1045. declaration in which a typedef name can be redefined, and once for
  1046. parsing a declaration in which that can't be done.  Here is a part of
  1047. the duplication, with actions omitted for brevity:
  1048.  
  1049.      initdcl:
  1050.                declarator maybeasm '='
  1051.                init
  1052.              | declarator maybeasm
  1053.              ;
  1054.      
  1055.      notype_initdcl:
  1056.                notype_declarator maybeasm '='
  1057.                init
  1058.              | notype_declarator maybeasm
  1059.              ;
  1060.  
  1061. Here `initdcl' can redeclare a typedef name, but `notype_initdcl'
  1062. cannot.  The distinction between `declarator' and `notype_declarator'
  1063. is the same sort of thing.
  1064.  
  1065. There is some similarity between this technique and a lexical tie-in
  1066. (described next), in that information which alters the lexical
  1067. analysis is changed during parsing by other parts of the program. 
  1068. The difference is here the information is global, and is used for
  1069. other purposes in the program.  A true lexical tie-in has a
  1070. special-purpose flag controlled by the syntactic context.
  1071.  
  1072.  
  1073. 
  1074. File: bison.info,  Node: Lexical Tie-ins,  Next: Tie-in Recovery,  Prev: Semantic Tokens,  Up: Context Dependency
  1075.  
  1076. Lexical Tie-ins
  1077. ===============
  1078.  
  1079. One way to handle context-dependency is the "lexical tie-in": a flag
  1080. which is set by Bison actions, whose purpose is to alter the way
  1081. tokens are parsed.
  1082.  
  1083. For example, suppose we have a language vaguely like C, but with a
  1084. special construct `hex (HEX-EXPR)'.  After the keyword `hex' comes an
  1085. expression in parentheses in which all integers are hexadecimal.  In
  1086. particular, the token `a1b' must be treated as an integer rather than
  1087. as an identifier if it appears in that context.  Here is how you can
  1088. do it:
  1089.  
  1090.      %{
  1091.      int hexflag;
  1092.      %}
  1093.      %%
  1094.      ...
  1095.      expr:   IDENTIFIER
  1096.              | constant
  1097.          | HEX '('
  1098.                      { hexflag = 1; }
  1099.                expr ')'
  1100.              { hexflag = 0;
  1101.                         $$ = $4; }
  1102.              | expr '+' expr
  1103.                      { $$ = make_sum ($1, $3); }
  1104.              ...
  1105.              ;
  1106.      
  1107.      constant:
  1108.                INTEGER
  1109.              | STRING
  1110.              ;
  1111.  
  1112. Here we assume that `yylex' looks at the value of `hexflag'; when it
  1113. is nonzero, all integers are parsed in hexadecimal, and tokens
  1114. starting with letters are parsed as integers if possible.
  1115.  
  1116. The declaration of `hexflag' shown in the C declarations section of
  1117. the parser file is needed to make it accessible to the actions (*note
  1118. C Declarations::.).  You must also write the code in `yylex' to obey
  1119. the flag.
  1120.  
  1121.  
  1122. 
  1123. File: bison.info,  Node: Tie-in Recovery,  Prev: Lexical Tie-ins,  Up: Context Dependency
  1124.  
  1125. Lexical Tie-ins and Error Recovery
  1126. ==================================
  1127.  
  1128. Lexical tie-ins make strict demands on any error recovery rules you
  1129. have.  *Note Error Recovery::.
  1130.  
  1131. The reason for this is that the purpose of an error recovery rule is
  1132. to abort the parsing of one construct and resume in some larger
  1133. construct.  For example, in C-like languages, a typical error
  1134. recovery rule is to skip tokens until the next semicolon, and then
  1135. start a new statement, like this:
  1136.  
  1137.      stmt:   expr ';'
  1138.              | IF '(' expr ')' stmt { ... }
  1139.              ...
  1140.              error ';'
  1141.                      { hexflag = 0; }
  1142.              ;
  1143.  
  1144. If there is a syntax error in the middle of a `hex (EXPR)' construct,
  1145. this error rule will apply, and then the action for the completed
  1146. `hex (EXPR)' will never run.  So `hexflag' would remain set for the
  1147. entire rest of the input, or until the next `hex' keyword, causing
  1148. identifiers to be misinterpreted as integers.
  1149.  
  1150. To avoid this problem the error recovery rule itself clears `hexflag'.
  1151.  
  1152. There may also be an error recovery rule that works within expressions.
  1153. For example, there could be a rule which applies within parentheses
  1154. and skips to the close-parenthesis:
  1155.  
  1156.      expr:   ...
  1157.              | '(' expr ')'
  1158.                      { $$ = $2; }
  1159.              | '(' error ')'
  1160.              ...
  1161.  
  1162.  If this rule acts within the `hex' construct, it is not going to
  1163. abort that construct (since it applies to an inner level of
  1164. parentheses within the construct).  Therefore, it should not clear
  1165. the flag: the rest of the `hex' construct should be parsed with the
  1166. flag still in effect.
  1167.  
  1168. What if there is an error recovery rule which might abort out of the
  1169. `hex' construct or might not, depending on circumstances?  There is
  1170. no way you can write the action to determine whether a `hex'
  1171. construct is being aborted or not.  So if you are using a lexical
  1172. tie-in, you had better make sure your error recovery rules are not of
  1173. this kind.  Each rule must be such that you can be sure that it
  1174. always will, or always won't, have to clear the flag.
  1175.  
  1176.  
  1177. 
  1178. File: bison.info,  Node: Debugging,  Next: Invocation,  Prev: Context Dependency,  Up: Top
  1179.  
  1180. Debugging Your Parser
  1181. *********************
  1182.  
  1183. If a Bison grammar compiles properly but doesn't do what you want
  1184. when it runs, the `yydebug' parser-trace feature can help you figure
  1185. out why.
  1186.  
  1187. To enable compilation of trace facilities, you must define the macro
  1188. `YYDEBUG' when you compile the parser.  You could use `-DYYDEBUG' as
  1189. a compiler option or you could put `#define YYDEBUG' in the C
  1190. declarations section of the grammar file (*note C Declarations::.). 
  1191. Alternatively, use the `-t' option when you run Bison (*note
  1192. Invocation::.).  I always define `YYDEBUG' so that debugging is
  1193. always possible.
  1194.  
  1195. The trace facility uses `stderr', so you must add
  1196. `#include <stdio.h>' to the C declarations section unless it is
  1197. already there.
  1198.  
  1199. Once you have compiled the program with trace facilities, the way to
  1200. request a trace is to store a nonzero value in the variable `yydebug'.
  1201. You can do this by making the C code do it (in `main', perhaps), or
  1202. you can alter the value with a C debugger.
  1203.  
  1204. Each step taken by the parser when `yydebug' is nonzero produces a
  1205. line or two of trace information, written on `stderr'.  The trace
  1206. messages tell you these things:
  1207.  
  1208.    * Each time the parser calls `yylex', what kind of token was read.
  1209.  
  1210.    * Each time a token is shifted, the depth and complete contents of
  1211.      the state stack (*note Parser States::.).
  1212.  
  1213.    * Each time a rule is reduced, which rule it is, and the complete
  1214.      contents of the state stack afterward.
  1215.  
  1216. To make sense of this information, it helps to refer to the listing
  1217. file produced by the Bison `-v' option (*note Invocation::.).  This
  1218. file shows the meaning of each state in terms of positions in various
  1219. rules, and also what each state will do with each possible input
  1220. token.  As you read the successive trace messages, you can see that
  1221. the parser is functioning according to its specification in the
  1222. listing file.  Eventually you will arrive at the place where
  1223. something undesirable happens, and you will see which parts of the
  1224. grammar are to blame.
  1225.  
  1226. The parser file is a C program and you can use C debuggers on it, but
  1227. it's not easy to interpret what it is doing.  The parser function is
  1228. a finite-state machine interpreter, and aside from the actions it
  1229. executes the same code over and over.  Only the values of variables
  1230. show where in the grammar it is working.
  1231.  
  1232.  
  1233. 
  1234. File: bison.info,  Node: Invocation,  Next: Table of Symbols,  Prev: Debugging,  Up: Top
  1235.  
  1236. Invocation of Bison; Command Options
  1237. ************************************
  1238.  
  1239. The usual way to invoke Bison is as follows:
  1240.  
  1241.      bison INFILE
  1242.  
  1243. Here INFILE is the grammar file name, which usually ends in `.y'. 
  1244. The parser file's name is made by replacing the `.y' with `.tab.c'. 
  1245. Thus, `bison foo.y' outputs `foo.tab.c'.
  1246.  
  1247. These options can be used with Bison:
  1248.  
  1249. `-d'
  1250.      Write an extra output file containing macro definitions for the
  1251.      token type names defined in the grammar and the semantic value
  1252.      type `YYSTYPE', as well as a few `extern' variable declarations.
  1253.  
  1254.      If the parser output file is named `NAME.c' then this file is
  1255.      named `NAME.h'.
  1256.  
  1257.      This output file is essential if you wish to put the definition
  1258.      of `yylex' in a separate source file, because `yylex' needs to
  1259.      be able to refer to token type codes and the variable `yylval'. 
  1260.      *Note Token Values::.
  1261.  
  1262. `-l'
  1263.      Don't put any `#line' preprocessor commands in the parser file. 
  1264.      Ordinarily Bison puts them in the parser file so that the C
  1265.      compiler and debuggers will associate errors with your source
  1266.      file, the grammar file.  This option causes them to associate
  1267.      errors with the parser file, treating it an independent source
  1268.      file in its own right.
  1269.  
  1270. `-o OUTFILE'
  1271.      Specify the name OUTFILE for the parser file.
  1272.  
  1273.      The other output files' names are constructed from OUTFILE as
  1274.      described under the `-v' and `-d' switches.
  1275.  
  1276. `-t'
  1277.      Output a definition of the macro `YYDEBUG' into the parser file,
  1278.      so that the debugging facilities are compiled.  *Note Debugging::.
  1279.  
  1280. `-v'
  1281.      Write an extra output file containing verbose descriptions of
  1282.      the parser states and what is done for each type of look-ahead
  1283.      token in that state.
  1284.  
  1285.      This file also describes all the conflicts, both those resolved
  1286.      by operator precedence and the unresolved ones.
  1287.  
  1288.      The file's name is made by removing `.tab.c' or `.c' from the
  1289.      parser output file name, and adding `.output' instead.
  1290.  
  1291.      Therefore, if the input file is `foo.y', then the parser file is
  1292.      called `foo.tab.c' by default.  As a consequence, the verbose
  1293.      output file is called `foo.output'.
  1294.  
  1295. `-y'
  1296.      Equivalent to `-o y.tab.c'; the parser output file is called
  1297.      `y.tab.c', and the other outputs are called `y.output' and
  1298.      `y.tab.h'.  The purpose of this switch is to imitate Yacc's
  1299.      output file name conventions.
  1300.  
  1301.  
  1302.